import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/about',
    name: 'about',
    meta: { requiredLogin: true },
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 页面需要认证，登录
  if(to.meta.requiredLogin){
    //检测 是否 有 token 令牌
    if(store.state.token){
      next( )
    }else(
      next({
        path: '/login',
        query: {redirect: to.path}
      })
    )
  } else {
    next()
  }
})
export default router
